package com.example.demo.mapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.model.dto.ActivityDTO;
import com.example.demo.model.entity.Activity;
import com.example.demo.model.entity.Prize;
import com.example.demo.util.Constants;
import com.mysql.cj.xdevapi.JsonString;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;

import java.util.List;

@Repository
public class RedisMapper {

    Jedis jedis = new Jedis("101.43.247.72", 6379);

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    public void setActivity(Integer activityId) {
        Activity activity = activityMapper.selectById(activityId);
        ActivityDTO activityDTO = buildActivity(activity);
        List<Prize> prizeList = activityPrizeMapper.selectByActivityId(activityId);
        activityDTO.setPrizeList(prizeList);
        String activityJSON = JSONObject.toJSONString(activityDTO);
        jedis.set("activity:" + activityDTO.getId(), activityJSON);
    }

    public ActivityDTO getActivity(Integer activityId) {
        String key = "activity:" + activityId;
        String activityJson = jedis.get(key);
        ActivityDTO activityDTO = JSON.parseObject(activityJson, ActivityDTO.class);
        return activityDTO;
    }

    private ActivityDTO buildActivity(Activity activity) {
        ActivityDTO activityDTO = new ActivityDTO();
        activityDTO.setId(activity.getId());
        activityDTO.setName(activity.getName());
        activityDTO.setStartTime(DateFormatUtils.format(activity.getStartTime(), Constants.timeFormat));
        activityDTO.setEndTime(DateFormatUtils.format(activity.getEndTime(), Constants.timeFormat));
        activityDTO.setChance(activity.getChance());
        return activityDTO;
    }
}
